package com.platform.system.model;

import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.platform.common.enums.ResultEnum;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.StringUtils;
import com.platform.system.domain.dto.AiRequestDto;
import com.platform.system.domain.dto.device.ModelAppInfoDto;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
/**
 * @author Huangkai
 */

@Slf4j
public class MiniMaxModel implements BaseModelHandle{

    @Override
    public boolean isCollection(JSONObject jsonObject) {
        ModelAppInfoDto modelAppInfoDto = jsonObject.toJavaObject(ModelAppInfoDto.class);
        JSONObject payload = new JSONObject();
        payload.put("model", "minimax-text-01");
        JSONObject systemContent = new JSONObject();
        JSONArray messages = new JSONArray();
        systemContent.put("content", "MM智能助理是一款由MiniMax自研的，没有调用其他产品的接口的大型语言模型。MiniMax是一家中国科技公司，一直致力于进行大模型相关的研究。");
        systemContent.put("role", "system");
        systemContent.put("name", "MM智能助理");
        messages.add(systemContent);
        JSONObject userContent = new JSONObject();
        userContent.put("content", "广州天气怎么样");
        userContent.put("role", "user");
        messages.add(userContent);
        payload.put("messages", messages);
        String result = requestModel(modelAppInfoDto, payload);
        if(StringUtils.isEmpty(result)){
            return false;
        }
        log.info("大模型的接口结果{}", result);
        JSONObject resultJson = JSONObject.parse(result);
        if(resultJson.containsKey("base_resp")){
            JSONObject response = resultJson.getJSONObject("base_resp");
            Integer statusCode = response.getInteger("status_code");
            if(statusCode !=null && statusCode == 0){
                return true;
            }
        }
        return false;

    }

    @Override
    public AiRequestDto requestAi(JSONObject jsonObject) {
        return null;
    }

    private String requestModel(ModelAppInfoDto modelAppInfoDto, JSONObject jsonObject){
        JSONObject param = JSONObject.parseObject(modelAppInfoDto.getModelParam());

        if(!param.containsKey("apiKey")){
            throw new BusinessException(ResultEnum.MODEL_COLLECTION_FAIL);
        }
        if(!param.containsKey("modelVersion")){
            throw new BusinessException(ResultEnum.MODEL_COLLECTION_FAIL);
        }
        if(!param.containsKey("groupId")){
            throw new BusinessException(ResultEnum.MODEL_COLLECTION_FAIL);
        }
        if(!param.containsKey("url")){
            throw new BusinessException(ResultEnum.MODEL_COLLECTION_FAIL);
        }
        log.info("参数{}", modelAppInfoDto.getModelParam());
        String apiKey = param.getString("apiKey");
        String groupId = param.getString("groupId");
        String url = param.getString("url") + "?GroupId=" + groupId;
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), jsonObject.toJSONString());
        // 创建 Request.Builder 来构建请求
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(body);
        // 设置请求头
        requestBuilder.addHeader("Authorization", "Bearer " + apiKey)
                .addHeader("User-Agent", "MyApp/1.0");
        Request request = requestBuilder.build();
        try{
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                return null;
            }
            log.info("结果{}", response);
            return response.body().string();
        }catch (IOException e){
            return null;
        }
    }

    public static void main(String[]args) {
        String groupId = "1862069927825915910";
        String apiKey = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJHcm91cE5hbWUiOiLmt7HlnLPpsbzkuq7np5HmioDmnInpmZDlhazlj7giLCJVc2VyTmFtZSI6IuS6keW5s-WPsOW8gOWPkei0puWPtyIsIkFjY291bnQiOiLkupHlubPlj7DlvIDlj5HotKblj7dAMTg2MjA2OTkyNzgyNTkxNTkxMCIsIlN1YmplY3RJRCI6IjE4NjIxMDc5NTYyODQyMzU3NzciLCJQaG9uZSI6IiIsIkdyb3VwSUQiOiIxODYyMDY5OTI3ODI1OTE1OTEwIiwiUGFnZU5hbWUiOiIiLCJNYWlsIjoiIiwiQ3JlYXRlVGltZSI6IjIwMjUtMDEtMjIgMDA6MTA6MzYiLCJUb2tlblR5cGUiOjEsImlzcyI6Im1pbmltYXgifQ.qgLrrRUrmCjhP-n10Hoi6x_jjlHYatYk38XqE8jHzER-zznNQRtuR5KFrDZo1MjcpppKt_EKkDyeQLWlC924nM7zmILUFg80camrH-tzY1DnaqKbdOyu4nTZkFvBqncLwvndC2cXctb1C3z1N_j9dATog75Kw_dzkOfD1mOn_lpVwVmJkN9wad2ec7R6Y_j_6t_v__gbVGiisNftQWSZlNKjdMDHdMjMr__0njk083V8zIbe0YLiok5ZfThoR-a7z4l4FFV37y9qJJPCkEuXKjlLsXyzYsInSo2-d59epT9yNhuaZIyzM5UwLFQGqG76xgzlHjrm0UAYzU1PY1GATA";
        String url = "https://api.minimax.chat/v1/text/chatcompletion_v2?GroupId=" + groupId;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("model", "minimax-text-01");
        JSONObject systemContent = new JSONObject();

        JSONArray messages = new JSONArray();
        systemContent.put("content", "MM智能助理是一款由MiniMax自研的，没有调用其他产品的接口的大型语言模型。MiniMax是一家中国科技公司，一直致力于进行大模型相关的研究。");
        systemContent.put("role", "system");
        systemContent.put("name", "MM智能助理");
        messages.add(systemContent);
        JSONObject userContent = new JSONObject();
        userContent.put("content", "广州天气怎么样？");
        userContent.put("role", "user");
        messages.add(userContent);
        jsonObject.put("messages", messages);
        OkHttpClient client = new OkHttpClient();
        log.info("内容{}", JsonUtils.toJson(messages));
        RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), jsonObject.toJSONString());
        // 创建 Request.Builder 来构建请求
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(body);
        // 设置请求头
        requestBuilder.addHeader("Authorization", "Bearer " + apiKey)
                .addHeader("User-Agent", "MyApp/1.0");

        Request request = requestBuilder.build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            System.out.println("结果" + response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
